//
//  MYNewsShopDetailsScenicspotOrderVC.m
//  MuYing
//
//  Created by tbb on 2020/3/10.
//  Copyright © 2020 TBB. All rights reserved.
//

#import "MYNewsShopDetailsScenicspotOrderVC.h"
#import "BRPickerView.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>

@interface MYNewsShopDetailsScenicspotOrderVC ()
@property (nonatomic, copy) NSString * message;

@property (nonatomic, copy) NSArray * infoTitleArr;
@property (nonatomic, copy) NSArray * infoPlaceholderArr;

@property (nonatomic, strong) MYShopSalesOrderBottonView * bottonView;
@property (nonatomic, copy) NSString * lodgerState;
@property (nonatomic, copy) NSString * lodgerRegion;

@property (nonatomic, copy) NSString * lastName;//姓
@property (nonatomic, copy) NSString * firstName;//名字
@property (nonatomic, copy) NSString * mailAddress;
@property (nonatomic, copy) NSString * mobile;
@property (nonatomic, copy) NSString * payTotal;
@property (nonatomic,retain) NSMutableDictionary *payParameters;
@property (nonatomic, copy) NSString * tickerNum;
@property (nonatomic,retain) NSTimer *timer;
@end

@implementation MYNewsShopDetailsScenicspotOrderVC
//景点详情页
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucceedAction) name:YJPaySucceedNotiKey object:nil];
    self.navigationItem.title = kYQLS(@"确定订单");
    self.infoTitleArr = @[kYQLS(@"名字"),kYQLS(@"姓氏"),kYQLS(@"国家/地区"),kYQLS(@"电子邮箱"),kYQLS(@"联络电话")];
    self.infoPlaceholderArr = @[kYQLS(@"请输入护照上名字"),kYQLS(@"请输入护照上姓氏"),kYQLS(@"请选择"),kYQLS(@"请输入电子邮箱"),kYQLS(@"请输入电话号码")];
}

-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    kYQREGISTERTABLEVIEWNIBCELL(@"MYNewsShopDetailsHotelOrderTimeCell");
    kYQREGISTERTABLEVIEWNIBCELL(@"MYNewsShopDetailsScenicspotTickerCell");
    kYQREGISTERTABLEVIEWNIBCELL(@"MYNewsShopDetailsHotelOrderInfoCell");
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRemarkCell class])
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRightLbCell class])
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRightBtnCell class])//选择优惠券
    kYQREGISTERTABLEVIEWNIBCELL(@"MYNewsShopDetailsHotelOrderHintCell");
    kYQREGISTERTABLEVIEWCHeaderFooter([MYShopDetailsTitleHeaderView class])
    kYQREGISTERTABLEVIEWCNIBHeaderFooter(@"MYNewsShopDetailsHotelOrderHintFooter")
    self.tickerNum = @"1";
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-kHeight_Botton_SafeArea-49-Height_NavBar);
    
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-kHeight_Botton_SafeArea);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    self.payTotal = self.ticketModel.ticketPrice;
    
}
#pragma mark - 景点订单提交
-(void)subOrderAction:(UIButton *)sender {
    
    
    if (!self.firstName) {
        kMBMesHUD(kYQLS(@"请填写名字"))
        return;
    }
    
    if (!self.lastName) {
        kMBMesHUD(kYQLS(@"请填写姓氏"))
        return;
    }
    
    if (!self.lodgerState || !self.lodgerRegion) {
        kMBMesHUD(kYQLS(@"请选择国家或地区"))
        return;
    }
    
    if (!self.mailAddress) {
        kMBMesHUD(kYQLS(@"请填写邮箱"))
        return;
    }
    
    if (!self.mobile) {
        kMBMesHUD(kYQLS(@"请填联系电话"))
        return;
    }

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"buyNumber"] = self.tickerNum;
    parameters[@"buyerMsg"] = self.message;
    //parameters[@"couponHistoryId"] = ;//优惠券ID，不使用就不需要传 , self.detailsModel.hotelId;
    parameters[@"isCoupon"] = @"0";
    
    parameters[@"sceneryId"] = self.detailsModel.sceneryId;
    parameters[@"sceneryStandardId"] = @(self.standardModel.standardId);
    parameters[@"sceneryTicketId"] = self.ticketModel.ticketId;

    parameters[@"lodgerEmail"] = self.mailAddress;
    parameters[@"lodgerName"] = [NSString stringWithFormat:@"%@ %@",self.firstName,self.lastName];
    parameters[@"lodgerPhone"] = self.mobile;
    parameters[@"lodgerRegion"] = self.lodgerRegion;
    parameters[@"lodgerState"] = self.lodgerState;
    
    parameters[@"entryTime"] = self.selectDateStr;
    
    [MYShopSalesOrderPayView shopSalesOrderPayView:self.payTotal :^(NSInteger index, NSString * typeStr) {
        [self getOrderPayType:index parameters:parameters];
    } :^{
        NSLog(@"");
    }];
}

//生成预计付订单
-(void)getOrderPayType:(NSInteger)type parameters:(NSDictionary *)parameters {

    YQSHOWLOADINGTIPS(kYQLS(@"正在提交"))
    [YQPNetWorkingManager sendPostRequest:kPOST_SUBMIT_SCENERY_ORDER_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            [self getPayDataOrderId:responseObject.data type:type];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error)
    }];
}

-(void)getPayDataOrderId:(NSString *)orderId type:(NSInteger)type {
    NSMutableDictionary *par = @{}.mutableCopy;
    par[@"orderId"] = orderId;
    par[@"payType"] = @(type + 1);
    par[@"orderType"] = @"3";
    self.payParameters=par;
    NSString *url=kALIPAY_ALIPAYPAYREQUEST_URL;
    if (type==1)//支付宝支付
    {
        url=kALIPAY_WECHATPAYPAYREQUEST_URL;
    }
    [YQPNetWorkingManager sendPostRequest:url parameters:par success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            if (type == 0) {
                [self goToAlipayData:responseObject.data];
            }
            else
            {
                NSDictionary *dict=(NSDictionary*)responseObject.data;
                PayReq* req= [[PayReq alloc] init];
                req.openID=[dict objectForKey:@"appId"];
                req.partnerId= [dict objectForKey:@"partnerId"];
                req.prepayId= [dict objectForKey:@"prepayId"];
                req.nonceStr = [dict objectForKey:@"nonceStr"];
                req.timeStamp= [[dict objectForKey:@"timestamp"] intValue];
                req.package= [dict objectForKey:@"packageStr"];
                req.sign= [dict objectForKey:@"sign"];
                [WXApi sendReq:req completion:^(BOOL success) {
                    NSLog(@"1");
                }];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
}

-(void)goToAlipayData:(NSString *)dataStr{
    NSString *appScheme = @"com.MuYing.www";
    [[AlipaySDK defaultService] payOrder:dataStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        //网页支付回调
        NSNotificationCenter *notiCenter=[NSNotificationCenter defaultCenter];
        //NSLog(@"result = %@",resultDic);
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultDic[@"memo"] isEqualToString:@""] && [resultStatus isEqualToString:@"9000"]) {
            /*支付成功通知*/
            [notiCenter postNotificationName:YJPaySucceedNotiKey object:self userInfo:nil];
        }else{
            
            if ([resultStatus isEqualToString:@"6001"]) {
                /*用户取消了支付*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    MBErrHUD(kYQLS(@"支付已取消"));
                });
            }else{
                NSString * strMsg = [NSString stringWithFormat:@"%@：%@,%@",kYQLS(@"支付结果"),kYQLS(@"支付失败"),resultDic[@"memo"]];
                NSLog(@"strMsg: %@",strMsg);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
    }];
}

-(void)paySucceedAction
{
   YQSHOWLOADINGINVIEW
   self.timer=[NSTimer scheduledTimerWithTimeInterval:2  target:self  selector:@selector(verifyPaymentResults) userInfo:nil  repeats:YES];
}

- (void)verifyPaymentResults
{
    [YQPNetWorkingManager sendPostRequest:kPAYRETURN parameters:self.payParameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            YQHIDELOADINGTIPS
            [self.timer invalidate];
            self.timer=nil;
            MYShopSalesOrderSucceedVC *succeedVC = [[MYShopSalesOrderSucceedVC alloc]initWithNibName:@"MYShopSalesOrderSucceedVC" bundle:nil];
            succeedVC.isIntegral = NO;
            succeedVC.navigationItem.title = kYQLS(@"支付成功");
            succeedVC.paySuceedLb.text = kYQLS(@"订单支付成功");
            succeedVC.paySuceedBtnText = kYQLS(@"查看我的订单");
            [self.navigationController pushViewController:succeedVC animated:true];
        }
        else if (responseObject.code==4) {
        }
        else
        {
                YQHIDELOADINGTIPS
                [self.timer invalidate];
                self.timer=nil;
                YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error)
        [self.timer invalidate];
        self.timer=nil;
    }];
}


#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else if(section == 3) {
        return self.infoTitleArr.count;
    }
    return 1;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MYNewsShopDetailsScenicspotTickerCell *tickerCell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsShopDetailsScenicspotTickerCell"];
            tickerCell.titleLb.text = self.detailsModel.name;
            tickerCell.specificationLb.text = self.ticketModel.ticketName;
            tickerCell.priceLb.text = [NSString stringWithFormat:@"HKD%@",self.ticketModel.ticketPrice];
            tickerCell.numLb.text = self.tickerNum;
            ws(self);
            tickerCell.selectNumBlock = ^(NSString * tickerNum) {
                weakself.tickerNum = tickerNum;
            };
            return tickerCell;
        }else if (indexPath.row == 1){
            MYNewsShopDetailsHotelOrderTimeCell *timeCell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsShopDetailsHotelOrderTimeCell"];
            timeCell.timeLb.text = [NSString stringWithFormat:@"%@：%@",kYQLS(@"入园日期"),self.selectDateStr];
            return timeCell;
        }else{
            MYShopSalesOrderRemarkCell *remarkCell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRemarkCell"];
            remarkCell.textLb.text = kYQLS(@"卖家留言");//44
            remarkCell.remarkTextField.text = self.message;
            ws(self);
            remarkCell.remarkTextBlock = ^(NSString * msg) {
                weakself.message = msg;
            };
            return remarkCell;
        }
    }else if (indexPath.section == 1) {
        MYShopSalesOrderRightLbCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRightLbCell"];
        cell.textLb.text = kYQLS(@"商品金额");
        cell.rightLb.textColor = kAPPThemeColor;
        cell.rightLb.text = [NSString stringWithFormat:@"HKD%@",self.ticketModel.ticketPrice];
        return cell;
    }else if (indexPath.section == 2) {
        MYNewsShopDetailsHotelOrderHintCell *orderHintCell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsShopDetailsHotelOrderHintCell"];
        orderHintCell.conentLb.text = kYQLS(@"该商品在支付成功后需等待卖家确认");
        return orderHintCell;
    }else{
        MYNewsShopDetailsHotelOrderInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsShopDetailsHotelOrderInfoCell"];
        infoCell.titleBtn.imageView.hidden = YES;
        infoCell.textField.userInteractionEnabled = YES;
        if (indexPath.row == 2) {
            infoCell.textField.userInteractionEnabled = NO;
            infoCell.titleBtn.imageView.hidden = NO;
            infoCell.titleBtn.imagePosition = QMUIButtonImagePositionRight;
            infoCell.titleBtn.spacingBetweenImageAndTitle = 0.0;
            [infoCell.titleBtn setImage:YQIMG(@"ShopDetails_more_icon") forState:(UIControlStateNormal)];
            if (self.lodgerState && self.lodgerRegion) {
                infoCell.textField.text = [NSString stringWithFormat:@"%@ %@",self.lodgerState,self.lodgerRegion];
            }
        }else if (indexPath.row == 0) {
            infoCell.textField.text = self.firstName;
        }else if (indexPath.row == 1) {
            infoCell.textField.text = self.lastName;
        }else if (indexPath.row == 3){
            infoCell.textField.text = self.mailAddress;
        }else{
            infoCell.textField.text = self.mobile;
        }
        infoCell.indexPath = indexPath;
        infoCell.textFiledBlock = ^(NSString * text, NSInteger row) {
            if (row == 0) {
                self.firstName = text;
            }else if (row == 1){
                self.lastName = text;
            }else if (row == 3){
                self.mailAddress = text;
            }else if (row == 4){
                self.mobile = text;
            }
        };

        [infoCell.titleBtn setTitle:self.infoTitleArr[indexPath.row] forState:(UIControlStateNormal)];
        infoCell.textField.placeholder = self.infoPlaceholderArr[indexPath.row];
        infoCell.titleBtn.userInteractionEnabled = NO;
        
        return infoCell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 124;
        }else if(indexPath.row == 1){
            return 35;
        }else{
            return 44;
        }
    }else if (indexPath.section == 2) {
        return 78;
    }else{
        return 58;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3 && indexPath.row == 2) {
        [BRAddressPickerView showAddressPickerWithShowType:(BRAddressPickerModeCity) defaultSelected:@[@"广东省", @"深圳市"] isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
            self.lodgerState = province.name;
            self.lodgerRegion = city.name;
            [self.listTableView reloadData];
        } cancelBlock:^{
            
        }];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        MYNewsShopDetailsHotelOrderHintFooter *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYNewsShopDetailsHotelOrderHintFooter"];
        footer.titleLb.text = [NSString stringWithFormat:@"%@\n%@",kYQLS(@"需与旅游证件一致"),kYQLS(@"继续操作即代表你同意使用条款和隐私政策")];
        return footer;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(section == 3) {
        return 56;
    }
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        MYShopDetailsTitleHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYShopDetailsTitleHeaderView"];
        headerView.titleLb.text = kYQLS(@"填写住客资料");
        return headerView;
    }else{
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        return 45;
    }
    return 0.001;;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
#pragma makr -- lazy
-(MYShopSalesOrderBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [MYShopSalesOrderBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        _bottonView.layer.shadowColor = HexColorA(0x000000, 0.6).CGColor;//RGB(70, 69, 69).CGColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:_bottonView.bounds].CGPath;
        [_bottonView.subOrderBtn setTitle:kYQLS(@"提交订单") forState:(UIControlStateNormal)];
        [_bottonView.subOrderBtn addTarget:self action:@selector(subOrderAction:) forControlEvents:(UIControlEventTouchUpInside)];
        _bottonView.priceLb.text = [NSString stringWithFormat:@"%@：$%@",kYQLS(@"总计"),self.ticketModel.ticketPrice];
    }
    return _bottonView;
}
#pragma makr -- lazy end
-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end

